package com.favoritemedium.util.geolocation;


/**
 * Implementation that uses Haversine's Formula
 * 
 * @author F. Azzam
 * 
 */
public class DistCalcHaversine extends BaseDistCalc implements IDistCalc {

	public DistCalcHaversine() {

	}

	public double calculateDistance(double lat1, double lon1, double lat2,
			double lon2, String unit) {

		/*
		 * Use Haversine formula to Calculate distance (in km) between two
		 * points specified by latitude/longitude (in numeric degrees)
		 */

		double R = 6371;
		double dLat = deg2rad(lat2 - lat1);
		double dLon = deg2rad(lon2 - lon1);
		double a = Math.sin(dLat / 2) * Math.sin(dLat / 2)
				+ Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
				* Math.sin(dLon / 2) * Math.sin(dLon / 2);
		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
		double dist = R * c;

		if (unit == "M") {
			dist = dist / 1.609344;
		} else if (unit == "N") {
			dist = dist / 1.852;
		}
		return (roundDouble(dist, 2));
	}

	public static void main(String[] args) {
		IDistCalc calculator = new DistCalcHaversine();
		System.out.println(calculator.calculateDistance(34.0333, -118.3667,
				3.1333, 101.5500, "K"));
	}
}

